package com.mb.mp.util;

import com.mb.common.utils.DateUtils;
import com.mb.common.utils.RedisUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 订单号工具
 *
 * @author michael.li
 * @create 2018-03-30 下午2:17
 **/
@Component
public class OrderUtil {
    private static final Logger logger = LoggerFactory.getLogger(OrderUtil.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 生成订单号
     * @param type 1:安装;2:维修;3:清洗
     * @return
     */
    public String genOrderId(String type){
        String orderId = "";
        //final IdGenerator idg = IdGenerator.INSTANCE;
        //String id = idg.nextId();

        String dateStr = DateUtils.format(new Date(),"yyyyMMdd");

        orderId = type + "0" + dateStr + RandomStringUtils.randomNumeric(8);
        String key = "order_id_" + dateStr;
        redisUtil.increment(key);
        int seq = (int)redisUtil.get(key);
        orderId += String.format("%08d",seq);
        return orderId;
    }

    /**
     * 生成支付订单号
     * @param type 1:微信 2:支付宝
     * @return
     */
    public String genPayOrderId(String type){
        String orderId = "";
        //final IdGenerator idg = IdGenerator.INSTANCE;
        //String id = idg.nextId();

        String dateStr = DateUtils.format(new Date(),"yyyyMMdd");

        orderId = type + "0" + dateStr + RandomStringUtils.randomNumeric(8);
        String key = "pay_order_id_" + dateStr;
        redisUtil.increment(key);
        int seq = (int)redisUtil.get(key);
        orderId += String.format("%06d",seq);
        orderId = "P" + type + "8"+ orderId;
        return orderId;
    }

    /**
     * 生成结算报表ID
     * @return
     */
    public String genFinSettleOrderId(){
        String orderId = "";

        String dateStr = DateUtils.format(new Date(),"yyyyMMdd");

        orderId = "f" + dateStr + RandomStringUtils.randomNumeric(8);
        String key = "fin_settle_order_id_" + dateStr;
        redisUtil.increment(key);
        int seq = (int)redisUtil.get(key);
        orderId += String.format("%06d",seq);
        return orderId;
    }

}
